<template>
  <div class="article-detail-container">
    <!-- <h2>params传参获取参数方式有2种</h2>
    <div>
      {{this.$route.params.articleId}}
    </div>
    <div>
      {{this.articleId}}
    </div> -->
    <!-- {{this.$route.query.articleId}} -->

    <!-- <h2>query传参获取参数方式有1种</h2>
    <div>
      {{this.$route.query.articleId}}
    </div> -->

    <!-- 文章导航部分 -->
    <van-nav-bar title="文章详情" left-arrow @click-left="$router.back()" />
    <!-- 内容部分 -->
    <div class="article-content">
      <!-- 文章标题 -->
      <h1 class="article-title">{{ article.title }}</h1>
      <!-- 作者信息 -->
      <van-cell class="author-info" center :border="false">
        <van-image
          class="author-photo"
          slot="icon"
          round
          fit="cover"
          :src="article.aut_photo"
        />
        <div class="author-name" slot="title">{{ article.aut_name }}</div>
        <div class="public-date" slot="label">{{ article.pubdate | relativeTime }}</div>
        <van-button
          class="follow-btn"
          :type="article.is_followed ? 'default' : 'info'"
          round
          :class="{ active: article.is_followed }"
          :icon="article.is_followed ? '' : 'plus'"
          :loading="isFollowLoading"
          @click="followBtnClick"
          >{{ article.is_followed ? "已关注" : "关注" }}</van-button
        >
      </van-cell>
      <!-- 文章正文 -->
      <div ref="article-content" class="markdown-body" v-html="article.content"></div>
      <!-- 评论列表 -->
      <comment-list 
        :articleId="articleId"
        :commentList="commentList"
        @updateCommentCount="commentCount = $event"
        @reply-btn-click="replyBtnClick"
      ></comment-list>
    </div>
    <!-- 文章详情的底部区域 -->
    <article-bottom-bar 
      :article="article"
      :commentCount="commentCount"
      @postCommentClick="isCommentPopshow = true"
    ></article-bottom-bar>

    <!-- 发布评论pop -->
    <!-- 不设置高度，则由内容撑开 -->
    <van-popup 
      v-model="isCommentPopshow" 
      position="bottom" 
      get-container="body"
    >
      <post-comment 
        :target="articleId"
        @post-success="postSuccess"
      />
    </van-popup>

    <!-- 回复 Popup -->
    <van-popup 
      v-model="isReplyPopshow" 
      position="bottom" 
      :style="{ height: '90%' }"
      get-container="body"
    >
      <!-- 这个comment-reply 懒加载情况 用v-if来进行条件渲染
      这里使用v-if的目的是让组件随着弹出层的显示进行渲染和销毁，防止加载过的组件不重新渲染导致数据不会重新加载的问题
      -->
      <comment-reply 
        :articleId="articleId"
        v-if="isReplyPopshow"
        :comment="replyComment"
        @close="isReplyPopshow = false"
      />
    </van-popup>

  </div>
</template>

<script>
/* 
在组件中获取动态路由参数：
如果是通过params传参：在组件中获取动态路由参数：
  方式1：this.$route.params.articleId
  方式2：props传参 （推荐）
    this.articleId

如果是通过query传参：在组件中获取动态路由参数：
方式1：this.$route.query.articleId

*/
import "./github-markdown.css";
import { getArticleDetailApi } from "@/api/article";
import { followUserApi, cancelFollowUserApi } from "@/api/user";
// 图片预览 必须单独加载引入
import { ImagePreview } from "vant";
import ArticleBottomBar from "./components/article-bottom-bar";
import CommentList from "./components/comment-list";
import PostComment from "./components/post-comment";
import CommentReply from "./components/comment-reply";
export default {
  name: "ArticleDetail",
  components: {
    ArticleBottomBar,
    CommentList,
    PostComment,
    CommentReply
  },
  props: {
    articleId: {
      type: [String, Number, Object],
      required: true,
    },
  },
  data() {
    return {
      // 文章详情对象
      article: {},
      // 关注用户按钮的loading状态
      isFollowLoading: false,
      // 展示pop
      isCommentPopshow: false,
      // 评论列表
      commentList: [],
      // 评论总数
      commentCount: 0,
      // 回复展示pop
      isReplyPopshow: false,
      // 当前回复评论对象
      replyComment: {}
    };
  },
  computed: {},
  watch: {},
  methods: {
    // 加载文章详情
    async loadArticleDetail() {
      const { data } = await getArticleDetailApi(this.articleId);
      this.article = data.data;
      console.log("输出详情页", data);

      // 数据改变影响视图更新（DOM数据）不是立即的。
      // 所以如果需要在修改数据之后马上操作被该数据影响的视图DOM，需要把这个代码放到$nextTick中

      // this.$nextTick是 Vue提供的一个方法
      // 参考文档：https://cn.vuejs.org/v2/api/#vm-nextTick
      this.$nextTick(() => {
        this.handlePreviewImage();
      });
    },
    //$nextTick 获取DOM，添加图片预览
    handlePreviewImage() {
      // 1. 获取文章内容DOM容器  vue获取dom,是通过ref。
      const articleContent = this.$refs["article-content"];
      // 2. 得到所有的 img 标签
      const imgs = articleContent.querySelectorAll("img");

      // 收集所有的图片路径
      const imgPaths = [];
      // 3. 循环img列表，给img注册点击事件
      imgs.forEach((img, index) => {
        imgPaths.push(img.src);
        img.onclick = function () {
          // 4. 在事件处理函数中调用 ImagePreview() 预览
          ImagePreview({
            images: imgPaths, //预览图片路径列表
            startPosition: index, //起始位置
          });
        };
      });
    },
    // 关注按钮点击
    followBtnClick() {
      this.isFollowLoading = true;
      if (this.article.is_followed) {
        // 取消关注用户
        this.cancelFollowUser();
      } else {
        // 关注用户
        this.followUser();
      }
      this.article.is_followed = !this.article.is_followed;
      this.isFollowLoading = false;
    },
    // 关注用户
    async followUser() {
      try {
        const { data } = await followUserApi(this.article.aut_id);
        // this.article.is_followed = true
        if (data.message === "OK" && data.data && data.data.target) {
          // this.$toast("关注成功")
        }
        console.log("关注用户", data);
      } catch (error) {
        this.$toast("关注失败");
      }
    },
    // 取消关注用户
    async cancelFollowUser() {
      try {
        // this.article.is_followed = false
        await cancelFollowUserApi(this.article.aut_id);
      } catch (error) {
        this.$toast("取消关注失败");
      }
    },
    // 发布评论成功
    postSuccess(comment) {
      // 把发布成功的评论数据对象放到评论列表顶部
      this.commentList.unshift(comment);
      // 发布成功，评论总数加1 
      this.commentCount ++;
      // 关闭发布评论弹出层
      this.isCommentPopshow = false;
    },
    // 点击回复
    replyBtnClick(comment){
      this.replyComment = comment;
      // 展示评论回复
      this.isReplyPopshow = true;
    }
  },
  created() {
    this.loadArticleDetail();
  },
  mounted() {},
};
</script>

<style lang="less" scoped>
//@import url(); 引入公共css类
// @import './github-markdown.css';
// @import 'github-markdown-css/github-markdown.css';

.article-detail-container {
  .van-nav-bar {
    background-color: #3296fa;
    /deep/ .van-nav-bar__title {
      color: #fff;
    }
    /deep/ .van-icon-arrow-left {
      color: #fff;
    }
  }
  .article-content {
    position: fixed;
    left: 0;
    right: 0;
    top: 46px;
    bottom: 44px;
    // overflow: scroll;
    overflow-y: auto;
    background-color: #fff;
    // 文章标题
    .article-title {
      font-size: 20px;
      color: #3a3a3a;
      padding: 10px;
      background-color: #fff;
      margin: 0;
    }
    // 作者信息
    .author-info {
      .author-photo {
        width: 50px;
        height: 50px;
        margin-right: 10px;
      }
      .author-name {
        color: #3a3a3a;
        font-size: 12px;
      }
      .public-date {
        color: #999999;
        font-size: 11px;
      }
      .follow-btn {
        width: 86px;
        height: 30px;
        background-color: #3296fa;
        color: #fff;
        border: unset;
      }
      .active {
        background-color: #999;
      }
    }

    // 文章内容
    .markdown-body {
      background-color: #fff;
      padding: 14px;
      ul {
        list-style: unset;
      }
    }
  }
}
</style>
